<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="池编号" prop="tankCode">
        <el-select
          v-model="queryParams.tankCode"
          placeholder="请选择池编号"
          clearable
          filterable
          style="width: 180px"
          @change="handleQuery"
        >
          <el-option
            v-for="item in tankOptions"
            :key="item.tankCode"
            :label="item.tankCode"
            :value="item.tankCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="投喂时间" style="width: 270px">
        <el-date-picker
          v-model="daterangeFeedTime"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['SysFeedingRecords:SysFeedingRecords:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['SysFeedingRecords:SysFeedingRecords:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['SysFeedingRecords:SysFeedingRecords:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="SysFeedingRecordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="池编号" align="center" prop="tankCode" />
      <el-table-column label="物资名称" align="center" prop="materialName" />
      <el-table-column label="批次号" align="center" prop="batchNumber" />
      <el-table-column label="投喂量" align="center" prop="amount" />
      <el-table-column label="残饵率" align="center" prop="residueRate" />
      <el-table-column label="损耗量" align="center" prop="quantity" />
      <el-table-column label="投喂时间" align="center" prop="feedTime" width="200">
        <template #default="{ row }">
          <span>{{ parseTime(row.feedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="创建者" align="center" prop="createBy" />-->
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="图片" align="center" prop="photoUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.photoUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['SysFeedingRecords:SysFeedingRecords:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['SysFeedingRecords:SysFeedingRecords:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="SysFeedingRecordsRef" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="10">
          <el-col :span="12">
            <!-- 步骤1：选择类别 -->
            <el-form-item label="物资类别" prop="category">
              <el-select
                  v-model="form.category"
                  placeholder="请选择物资类别"
                  @change="handleCategoryChange"
                  clearable
              >
                <el-option
                    v-for="item in categoryOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
            <el-col :span="12">
              <el-form-item label="模板选择" prop="modelName">
                <el-select
                    v-model="form.modelName"
                    placeholder="请选择模板"
                    clearable
                    filterable
                    @change="handleTemplateChange"
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in modelOptions"
                      :key="item.modelName"
                      :label="item.modelName"
                      :value="item.modelName"
                  />
                </el-select>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <!-- 步骤2：根据类别选择名称 -->
            <el-form-item label="物资名称" prop="materialName">
              <el-select
                  v-model="form.materialName"
                  placeholder="请选择物资名称"
                  @change="handleNameChange"
                  :disabled="!form.category"
                  clearable
              >
                <el-option
                    v-for="item in nameOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="池编号" prop="tankId">
              <el-select v-model="form.tankId" placeholder="请选择桶编号" clearable>
                <el-option
                    v-for="item in tankOptions"
                    :key="item.id"
                    :label="item.tankCode"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNumber">
              <el-select v-model="form.batchNumber" @change="handleBatchChange" placeholder="请选择批次号">
                <el-option
                    v-for="item in batchOptions"
                    :key="item.batchNumber || item"
                    :label="item.batchNumber || item"
                    :value="item.batchNumber || item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">

        <!-- 步骤3：根据类别+名称加载批次号 -->
        <!-- <el-form-item label="批次号" prop="batchNumber">
          <el-select
            v-model="form.batchNumber"
            @change="handleBatchChange"
            placeholder="请选择批次号"
          >
            <el-option
              v-for="item in batchOptions"
              :key="item.id"
              :label="item.batchNumber"
              :value="item.batchNumber"
            />
          </el-select>
        </el-form-item> -->
            <el-form-item label="投喂量" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入投喂量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <!-- 物资编码 -->
            <el-form-item label="物资编码" prop="materialCode">
              <el-select v-model="form.materialCode" @change="handleCodeChange" placeholder="请选择物资编码">
                <el-option
                    v-for="item in codeOptions"
                    :key="item.id"
                    :label="item.materialCode"
                    :value="item.materialCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="残饵率" prop="residueRate">
              <el-input v-model="form.residueRate" placeholder="请输入残饵率" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="损耗量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入损耗量" />
        </el-form-item>
        <el-form-item label="投喂时间" prop="feedTime">
          <el-date-picker
            v-model="form.feedTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择投喂时间"
            style="width: 500px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传图片" prop="photoUrl">
          <image-upload v-model="form.photoUrl"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysFeedingRecords">
import { ref, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter} from 'vue-router'
import {
  listSysFeedingRecords,
  getSysFeedingRecords,
  addSysFeedingRecords,
  updateSysFeedingRecords,
  delSysFeedingRecords
} from "@/api/SysFeedingRecords/SysFeedingRecords"
import { listSysTanks } from "@/api/SysTanks/SysTanks"
import { listCategories, listNamesByCategory, fetchBatchRecords, listBatches } from "@/api/SysFeedingRecords/material"
import { watch } from 'vue'
import { listSysModelFeeding } from '@/api/SysModel/SysModelFeeding'
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

// 响应式数据
const SysFeedingRecordsList = ref([])
const tankOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const codeOptions = ref([])   // 编码列表
const modelOptions = ref([])   // 模板列表
// 表单与查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  tankCode: null,
  tankId: null,
  feedTime: null,
  beginFeedTime: null,
  endFeedTime: null,
  modelName: null
})
const daterangeFeedTime = ref([])
const form = ref({
  id: null,
  tankId: null,
  category: '',           // 类别
  materialName: '',       // 名称
  batchNumber: '',        // 批次号
  materialCode: '',       // 编码（由批次号决定）
  inventoryId: null,      // 批次记录ID（用于提交）
  feedType: '',           // 饲料类型（由批次决定）
  amount: null,
  residueRate: null,
  feedTime: null,
  remark: null,
  photoUrl: null,
  modelName: null,
  quantity: null// 模板名称
})

// const rules = ref({
//   tankId: [{ required: true, message: "桶编号不能为空", trigger: "change" }],
//   category: [{ required: true, message: "请选择物资类别", trigger: "change" }],
//   materialName: [{ required: true, message: "请选择物资名称", trigger: "change" }],
//   batchNumber: [{ required: true, message: "请选择批次号", trigger: "change" }],
//   amount: [{ pattern: /^([1-9]\d{0,8}|0)(\.\d{1,2})?$/, message: "投喂量必须为数字，最多9位整数，2位小数", trigger: "blur" }],
//   residueRate: [{ pattern: /^(0(\.\d{1,2})?|1(\.0{1,2})?)$/, message: "残饵率必须为0~1之间的数字，最多2位小数", trigger: "blur" }]
// })
const rules = ref({
  tankId: [{ required: true, message: "池编号不能为空", trigger: "change" }],
  category: [{ required: true, message: "请选择物资类别", trigger: "change" }],
  materialName: [{ required: true, message: "请选择物资名称", trigger: "change" }],
  batchNumber: [{ required: true, message: "请选择批次号", trigger: "change" }],
  amount: [
    { required: true, message: "投喂量不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "投喂量必须为数字，最多保留两位小数", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value && Number(value) > 999999999) {
          callback(new Error("投喂量过大，请输入不超过 999999999 的数值"))
        } else {
          callback()
        }
      },
      trigger: "blur"
    }
  ],
  residueRate: [
    // { required: true, message: "残饵率不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "残饵率必须为数字，最多保留两位小数", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value && (Number(value) < 0 || Number(value) > 1)) {
          callback(new Error("残饵率必须在 0~1 之间"))
        } else {
          callback()
        }
      },
      trigger: "blur"
    }
  ],
  feedTime: [{ required: true, message: "投喂时间不能为空", trigger: "change" }],
  quantity: [
    // { required: true, message: "损耗量不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "损耗量必须为正数，最多保留两位小数", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const num = Number(value);
        if (num <= 0) {
          callback(new Error("损耗量必须为大于0的正数"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
})
// 下拉选项
const categoryOptions = ref([])  // 类别
const nameOptions = ref([])      // 名称
const batchOptions = ref([])     // 批次列表

// 获取喂养模板列表
function getModelOptions() {
  listSysModelFeeding({ pageNum: 1, pageSize: 999 })
    .then(res => {
      modelOptions.value = res.rows || []
    })
    .catch(err => {
      console.error('获取喂养模板失败:', err)
      proxy.$modal.msgError('获取模板数据失败')
    })
}

/** 选择模板后自动填充桶高和容积 */
function handleTemplateChange(modelName) {
  if (!modelName) return // 清空选择时不处理

  const selected = modelOptions.value.find(m => m.modelName === modelName)
  if (selected) {
    // 自动填充但不覆盖用户可能已输入的内容（除非你希望强制覆盖）
    if (!form.value.category) {
      form.value.category = selected.category
    }
    if (!form.value.materialName) {
      form.value.materialName = selected.materialName
    }
    if (!form.value.batchNumber) {
      form.value.batchNumber = selected.batchNumber
    }
    if (!form.value.materialCode) {
      form.value.materialCode = selected.materialCode
    }

    // 可选：强制覆盖（更符合“选择模板”的语义）
    form.value.category = selected.category
    form.value.materialName = selected.materialName
    form.value.batchNumber = selected.batchNumber
    form.value.materialCode = selected.materialCode
  }
}


/**
 * 通用接口响应处理函数
 * 适配后端常见的响应格式：{code: 200, msg: "success", data: ...}
 */
const handleResponse = (response) => {
  // 检查是否为标准响应格式
  if (response && typeof response === 'object') {
    // 如果有code字段且不为200，视为错误
    if ('code' in response && response.code !== 200) {
      throw new Error(response.msg || '接口请求失败');
    }
    // 返回数据部分，优先取data字段
    return response.data !== undefined ? response.data : response;
  }
  return response;
};

/**
 * 加载物资类别
 * 适配后端返回格式：{code:200, data: ["类别1", "类别2"]}
 */
async function loadCategories() {
  try {
    const response = await listCategories();
    const data = handleResponse(response);
    
    // 确保返回的是数组
    if (Array.isArray(data)) {
      categoryOptions.value = data;
      console.log('加载物资类别成功:', data);
    } else {
      proxy.$modal.msgError("物资类别数据格式异常");
      categoryOptions.value = [];
    }
  } catch (err) {
    proxy.$modal.msgError("加载物资类别失败: " + (err.message || err));
    console.error("加载物资类别错误:", err);
    categoryOptions.value = [];
  }
}

/**
 * 类别变化：清空后续字段，加载名称
 * 适配后端返回格式：{code:200, data: ["名称1", "名称2"]}
 */
function handleCategoryChange(category) {
  // 重置后续字段
  form.value.materialName = '';
  form.value.batchNumber = '';
  form.value.materialCode = '';
  form.value.inventoryId = null;
  form.value.feedType = '';

  // 重置下拉选项
  nameOptions.value = [];
  batchOptions.value = [];

  if (!category) return;

  // 加载物资名称
  listNamesByCategory(category)
    .then(response => {
      const data = handleResponse(response);
      // 确保返回的是数组
      if (Array.isArray(data)) {
        nameOptions.value = data;
        console.log('加载物资名称成功:', data);
      } else {
        proxy.$modal.msgWarning("未查询到相关物资名称");
        nameOptions.value = [];
      }
    })
    .catch(err => {
      proxy.$modal.msgError("加载物资名称失败: " + (err.message || err));
      console.error("加载物资名称错误:", err);
    });
}


async function handleNameChange(name) {
  form.value.batchNumber = '';
  form.value.materialCode = '';
  form.value.inventoryId = null;
  batchOptions.value = [];
  codeOptions.value = [];

  if (!form.value.category || !name) return;

  try {
    const response = await fetchBatchRecords(form.value.category, name);
    const batches = handleResponse(response);

    // 如果返回的是对象数组，提取 batchNumber
    if (Array.isArray(batches)) {
      batchOptions.value = batches.map(b => b.batchNumber || b);
    }
  } catch (err) {
    proxy.$modal.msgError("加载批次号失败: " + err.message);
  }
}

async function handleBatchChange(batchNumber) {
  form.value.materialCode = '';
  form.value.inventoryId = null;
  codeOptions.value = [];

  if (!batchNumber) return;

  try {
    const response = await listBatches(form.value.category, form.value.materialName, batchNumber);
    const details = handleResponse(response); 
    // 例: [{id: 9, materialCode: "DS006"}, {id: 10, materialCode: "DS007"}]

    if (Array.isArray(details)) {
      codeOptions.value = details;
      if (details.length === 1) {
        form.value.materialCode = details[0].materialCode;
        form.value.inventoryId = details[0].id;
      }
    }
  } catch (err) {
    proxy.$modal.msgError("加载物资编码失败: " + err.message);
  }
}

// step3: 选中物资编码 -> 记录 inventoryId
function handleCodeChange(materialCode) {
  const selected = codeOptions.value.find(item => item.materialCode === materialCode);
  if (selected) {
    form.value.inventoryId = selected.id;
  }
}


/**
 * 获取桶列表
 */
function getTankOptions() {
  listSysTanks({ pageNum: 1, pageSize: 1000,isFinished: '1'})
    .then(response => {
      const data = handleResponse(response);
      tankOptions.value = data.rows || [];
      console.log('加载桶列表成功:', data.rows);
    })
    .catch(err => {
      proxy.$modal.msgError("加载池列表失败: " + (err.message || err));
      console.error("加载池列表错误:", err);
    });
}

/**
 * 查询列表
 */
function getList() {
  loading.value = true

  if (daterangeFeedTime.value && daterangeFeedTime.value.length === 2) {
    queryParams.value.beginFeedTime = daterangeFeedTime.value[0]
    queryParams.value.endFeedTime = daterangeFeedTime.value[1]
  } else {
    queryParams.value.beginFeedTime = null
    queryParams.value.endFeedTime = null
  }

  listSysFeedingRecords(queryParams.value).then(response => {
    SysFeedingRecordsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}




/**
 * 搜索 / 重置
 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


// function resetQuery() {
//   proxy.resetForm("queryRef");
//   handleQuery();
// }
function resetQuery() {
  daterangeFeedTime.value = []
  queryParams.value.beginFeedTime = null
  queryParams.value.endFeedTime = null
  queryParams.value.tankCode = null   // 清空桶编号
  queryParams.value.tankId = null
  proxy.resetForm("queryRef")
  handleQuery()
}

/**
 * 多选处理
 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/**
 * 新增
 */
async function handleAdd() {
  reset();
  getTankOptions();
  await loadCategories(); // 等待物资类别加载
  open.value = true;
  title.value = "添加投喂记录";
}

/**
 * 修改（回显）
 */
async function handleUpdate(row) {
  reset();
  getTankOptions();

  try {
    const response = await getSysFeedingRecords(row.id);
    const data = handleResponse(response);
    form.value = { ...data };

    await loadCategories();

    if (data.category) {
      form.value.category = data.category;
      const nameRes = await listNamesByCategory(data.category);
      nameOptions.value = handleResponse(nameRes) || [];

      if (data.materialName) {
        form.value.materialName = data.materialName;

        // 先加载批次号和详情
        const batchRes = await fetchBatchRecords(data.category, data.materialName);
        const batchRecords = handleResponse(batchRes);
        const batchNumbers = Array.isArray(batchRecords) 
          ? batchRecords.map(item => item.batchNumber) 
          : [];

        const detailPromises = batchNumbers.map(async (bn) => {
          try {
            const res = await listBatches(data.category, data.materialName, bn);
            const details = handleResponse(res);
            if (Array.isArray(details) && details.length > 0) {
              const item = details[0];
              return {
                id: item.id,
                materialCode: item.materialCode,
                batchNumber: bn
              };
            }
            return null;
          } catch (e) {
            return null;
          }
        });

        const details = await Promise.all(detailPromises);
        batchOptions.value = details.filter(d => d !== null);

        // 最后设置 batchNumber，触发回显
        if (data.batchNumber) {
          form.value.batchNumber = data.batchNumber;
          const selected = batchOptions.value.find(b => b.batchNumber === data.batchNumber);
          if (selected) {
            form.value.inventoryId = selected.id;
            form.value.materialCode = selected.materialCode;
          } else {
            proxy.$modal.msgWarning("当前批次在库存中不存在");
          }
        }
      }
    }
  } catch (err) {
    proxy.$modal.msgError("回显失败：" + err.message);
  }

  open.value = true;
  title.value = "修改投喂记录";
}

function submitForm() {
  proxy.$refs.SysFeedingRecordsRef.validate(async valid => {
    if (!valid) return;

    if (!form.value.inventoryId) {
      proxy.$modal.msgError("请选择批次号和物资编码");
      return;
    }

    const payload = {
      id: form.value.id || undefined,
      tankId: Number(form.value.tankId),
      //batchNumber: form.value.batchNumber,     // 字符串
      //materialCode: form.value.materialCode,   // 字符串
      inventoryId: form.value.inventoryId,     // 数字
      amount: Number(form.value.amount),
      residueRate: Number(form.value.residueRate),
      feedTime: form.value.feedTime,
      remark: form.value.remark || undefined,
      photoUrl: typeof form.value.photoUrl === "string" ? form.value.photoUrl : undefined,
      quantity: Number(form.value.quantity) // 添加损耗量字段
    };
    console.log("提交的数据:", JSON.stringify(payload, null, 2));

    try {
      if (payload.id) {
        await updateSysFeedingRecords(payload);
        proxy.$modal.msgSuccess("修改成功");
      } else {
        await addSysFeedingRecords(payload);
        proxy.$modal.msgSuccess("新增成功");
      }
      open.value = false;
      getList();
    } catch (err) {
      proxy.$modal.msgError("提交失败: " + (err.message || err));
      console.error("错误详情:", err);
    }
  });
}

/**
 * 删除
 */
function handleDelete(row) {
  const deleteIds = row.id || ids.value;
  proxy.$modal.confirm(`是否确认删除编号为 "${deleteIds}" 的数据项？`).then(() => {
    return delSysFeedingRecords(deleteIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/**
 * 取消
 */
function cancel() {
  open.value = false;
  reset();
}

/**
 * 重置表单
 */
function reset() {
  form.value = {
    id: null,
    tankId: null,
    category: '',
    materialName: '',
    batchNumber: '',
    materialCode: '',
    inventoryId: null,
    feedType: '',
    amount: null,
    residueRate: null,
    feedTime: null,
    remark: null,
    photoUrl: null,
    modelName: null
  };
  proxy.resetForm("SysFeedingRecordsRef");
}

// 页面初始化
onMounted(async () => {
  await getTankOptions()
  loadCategories()

  // 只有带参进来时，自动按桶查询一次
  if (route.query.tankCode) {
    queryParams.value.tankCode = route.query.tankCode
    const tank = tankOptions.value.find(t => t.tankCode === route.query.tankCode)
    queryParams.value.tankId = tank ? tank.id : null
    queryParams.value.pageNum = 1
    getList()

   // 关键：把 URL 上的 tankCode 去掉，避免后续 watch 又把它写回来
   const { tankCode, ...rest } = route.query
   router.replace({ query: { ...rest } })
  } else {
    // 不带参时是否默认加载全量，看你的需要；要默认加载就保留：
    getList()
  }
  getModelOptions()
})

// 监听路由参数变化（比如切换不同的养殖桶跳转）
watch(
  () => route.query.tankCode,
  (newTankCode) => {
    if (newTankCode) {
      queryParams.value.tankCode = newTankCode
      const tank = tankOptions.value.find(t => t.tankCode === newTankCode)
      queryParams.value.tankId = tank ? tank.id : null
    } else {
      queryParams.value.tankCode = null
      queryParams.value.tankId = null
    }
    queryParams.value.pageNum = 1
    getList()   // 立刻刷新
  }
)
</script>